# pretty print the lhs and rhs of a production so it can be added to a .fcfg file
from nltk.featstruct import *

from nltk.grammar import FeatStructNonterminal 

def prod_cmp(x, y):
    xprod = ProductionPrinter(x)
    yprod = ProductionPrinter(y)
    if xprod.getLeftType() > yprod.getLeftType():
        return 1
    elif xprod.getLeftType() == yprod.getLeftType():
        return 0
    else: # x<y
        return -1    

class ProductionPrinter:
    
    def __init__(self, production):
        self.production = production
           
    def getLeftType(self):
        featDict = FeatDict(self.production.lhs())
        ftype = Feature("type")
        return str(featDict[ftype])
    
    def getLeft(self):
        featDict = FeatDict(self.production.lhs())
        #return "L:" + str(self.production.lhs())
        #print featDict["*type*"]
        return str(featDict._repr(featDict._find_reentrances({}), {}))
    
    def getRight(self):
        #print len(self.production.rhs())
        #print list(self.production.rhs())
        
        string_list = []
        for part in list(self.production.rhs()):
            #featDict = FeatDict(part)
            #featstring = str(featDict._repr(featDict._find_reentrances({}), {}))
            #print FeatStruct(part)
            #fp = FeatStructParser()
            #fp.parse(part)
            if isinstance(part, FeatStructNonterminal):
                #print "FeatStructNonterminal"
                fstruct = FeatStructNonterminal(part)
                part = str(fstruct._repr(fstruct._find_reentrances({}), {}))
            else:
                part = "'" + part + "'"
            string_list.append(part)
        #return "R:" + str(self.production.rhs())
        return ' '.join(string_list)
    
            #featDict = FeatDict(prod.lhs())
            #filestore.writeLine(featDict._repr(featDict._find_reentrances({}), {}))
